/**
 * 安卓白金英雄坛制作组 <br>
 * 文件名：LoadingScreen.java <br>
 * 创建时间：2013-5-20 下午4:34:51 <br>
 * 所属项目：GmudEX <br>
 * @author 12548 <br>
 */
package lostland.gmud.exv2;

import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import cn.bmob.v3.update.BmobUpdateAgent;
import lostland.gmud.exv2.Gmud.PaymentStatus;
import lostland.gmud.exv2.blgframework.BasicScreen;
import lostland.gmud.exv2.blgframework.IGraphics;
import lostland.gmud.exv2.blgframework.IGraphics.PixmapFormat;
import lostland.gmud.exv2.blgframework.IPixmap;
import lostland.gmud.exv2.blgframework.Music;
import lostland.gmud.exv2.blgframework.impl.BLGFileIO;
import lostland.gmud.exv2.blgframework.impl.BLGGraphics;
import lostland.gmud.exv2.data.Gesture;
import lostland.gmud.exv2.data.GmudMap;
import lostland.gmud.exv2.data.IngameData;
import lostland.gmud.exv2.data.ItemTemplate;
import lostland.gmud.exv2.data.MapExtraInfo;
import lostland.gmud.exv2.data.Npc;
import lostland.gmud.exv2.data.Room;
import lostland.gmud.exv2.data.SaveData;
import lostland.gmud.exv2.data.Skill;
import lostland.gmud.exv2.data.TriggerCondition;
import lostland.gmud.exv2.data.TriggerEvent;
import lostland.gmud.exv2.expand.DesUtils;
import lostland.gmud.exv2.ui.StartScreen;
import lostland.gmud.exv2.ui.core.FullScreen;
import lostland.gmud.exv2.ui.core.NewButton;


/**
 * 类名：LoadingScreen <br>
 * 说明：加载游戏进度或初始数据
 *
 * @author 12548
 */
public class LoadingScreen extends FullScreen {

	boolean b = false;
	public static volatile boolean b2 = false;


	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#update(float)
	 */
	@Override
	public void update(float deltaTime) {

		if (b2) {
			super.update(deltaTime);
			return;
		}

		Logger.e("Loading Start");
		BasicScreen.setTimeFlowing(false);

		BLGFileIO f = (BLGFileIO) getGame().getFileIO();

		if (!b) return;

		loadBasicDatas();

		MapScreen.C_ROWS = GameConstants.RES_W[Game.resolution_level];
		MapScreen.C_COLUMNS = GameConstants.RES_H[Game.resolution_level];
		getGame().mapFB = Bitmap.createBitmap(GameConstants.RES_W[Game.resolution_level] * MapTile.TILE_WIDTH,
				GameConstants.RES_H[Game.resolution_level] * MapTile.TILE_WIDTH, Config.ARGB_8888);

		((BLGGraphics) getGame().getGraphics()).mapCanvas = new Canvas(getGame().mapFB);


		BmobUpdateAgent.setUpdateOnlyWifi(Game.updateonlyonwifi);
		getGame().getHandler().obtainMessage(GameMessageHandler.MSG_AUTOUPDATE).sendToTarget();

		SharedPreferences sp = f.getPreferences();

		SaveData save = getSave(sp.getString("save", "DE}{FAULT"));

		if (save != null) {
			getGame().oldmc = save.oldmc;
		}

		if (save == null || sp.getBoolean("newgame", true)) {
			Logger.e("New Got");
			new StartScreen().insertToGame();
		} else {

			if (sp.getBoolean("newgame", true)) {
				Logger.e("New Got");
				new StartScreen().insertToGame();
				return;
			}

			Game.getInstance().data = save.data;
			Gmud.mc = save.mc;
			new Room().after_process();
			Gmud.mc.refreshItems();


			MapScreen.getInstance().jumpTo(1, 9, 7, Direction.DOWN);
			Gmud.mc.id = -1;

			if (Gmud.paymentData.paymentStatus == PaymentStatus.PAID) {
				getGame().setRectangleStone(getGame().uname);
			}

		}

		b2 = true;
	}


	/**
	 * 加载基础数据。
	 */
	public static void loadBasicDatas() {
		loadAssets();

		//		AssetManager mgr = ((Context)instance).getAssets();
		//		Assets.songti = Typeface.createFromAsset(mgr, "simhei.ttf");

		loadConditionsJson();
		loadEventsJson();
		loadGestureJson();
		loadSkillJson();
//		loadItemJson();
//		Item.nullItem = Item.generateItem(0, -1);

		loadMaps();
//		loadNpcs();

		loadMEIJson();

		///////////////////////////////////////////////////
		IngameData.getInstance().m1npc = -1;
		IngameData.getInstance().m2itm = -1;
		IngameData.getInstance().m3npc = -1;
//		TalkingScreen.mtutuitm = -1;

		IngameData.getInstance().m1 = false;
		IngameData.getInstance().m2 = false;
		IngameData.getInstance().m3 = false;
//		TalkingScreen.mtutu = false;
		getGame().data.mdone = false;

		/////////////////////////////////////////////////


		//		Gmud.mms = new MainMenuScreen(game);
		//		Gmud.ms = new MapScreen(game);

		new Room().exec();
	}


	private SaveData getSave(final String saveString) {
		SaveData fromJson;
		try {
			fromJson = new Gson().fromJson(new DesUtils().decrypt(saveString), SaveData.class);
			return fromJson;
		} catch (Exception e) {
			return null;
		}

	}

	@SuppressWarnings("unused")
	private int ReadInt16Signed(InputStream is) {
		int result = 0;
		result = ReadInt(2, is);
		if (result > 0x7FFF) {
			result -= 0x10000;
		}

		return result;
	}

	private int ReadInt(int byteCnt, InputStream is) {
		int result = 0;
		for (int i = 0; i < byteCnt; i++) {
			try {
				result |= ((is.read() & 0xFF) << (i << 3));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public IPixmap loading1, loading2;

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#present(float)
	 */
	@Override
	public void present(float deltaTime) {

		IGraphics g = getGame().getGraphics();

		if (loading1 == null) {
			loading1 = g.newPixmap("newloading1.png", PixmapFormat.RGB565);
		}
		if (loading2 == null) {
			loading2 = g.newPixmap("newloading2.png", PixmapFormat.RGB565);
		}
//		if(!b2) {
//			g.drawPixmap(loading1, 0, 0);
//		} else {
//			g.drawPixmap(loading2, 0, 0);
//		}

		b = true;

	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#pause()
	 */
	@Override
	public void pause() {

	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#resume()
	 */
	@Override
	public void resume() {

	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#dispose()
	 */
	@Override
	public void dispose() {
	}


	public static void loadAssets() {
		IGraphics g = Game.getInstance().getGraphics();

		Assets.mainchar = new IPixmap[3];
		Assets.mainchar_famale = new IPixmap[3];
		Assets.maptile = new IPixmap[3];

		for (int i = 0; i < 3; i++) {
			Assets.mainchar[i] = g.newPixmap(String.format("mainchar%d.png", i), PixmapFormat.ARGB8888);
			Assets.mainchar_famale[i] = g.newPixmap(String.format("mainchar_famale%d.png", i), PixmapFormat.ARGB8888);
			Assets.maptile[i] = g.newPixmap(String.format("ytty%d.png", i), PixmapFormat.ARGB8888);
		}

		Assets.arrow = g.newPixmap("arrow.png", PixmapFormat.ARGB8888);
		Assets.empty = g.newPixmap("empty.png", PixmapFormat.ARGB8888);
		Assets.filled = g.newPixmap("filled.png", PixmapFormat.ARGB8888);
		Assets.checked = g.newPixmap("checked.png", PixmapFormat.ARGB8888);
		Assets.checkedfilled = g.newPixmap("checkedfilled.png", PixmapFormat.ARGB8888);
		Assets.vs = g.newPixmap("vs.png", PixmapFormat.ARGB8888);
		Assets.hpfp = g.newPixmap("hpfp.png", PixmapFormat.ARGB8888);
		Assets.boom = g.newPixmap("boom.png", PixmapFormat.ARGB8888);
		Assets.transfixed = g.newPixmap("transfixed.png", PixmapFormat.ARGB8888);

		Assets.left = g.newPixmap("leftt.png", PixmapFormat.ARGB8888);
		Assets.right = g.newPixmap("rightt.png", PixmapFormat.ARGB8888);

		Assets.btns = new HashMap<>();
		for (int i = 0; i < NewButton.colorstr.length; i++) {
			for (NewButton j : NewButton.values()) {
				if (j != NewButton.NB_NULL) {
					Assets.btns.put(NewButton.colorstr[i] + j.namestr(),
							g.newPixmap(String.format("btns/%s/normal/images/nb%s.png",
									NewButton.colorstr[i], j.namestr()), PixmapFormat.ARGB8888));
				}
			}
		}

		Assets.btns_pressed = new HashMap<>();
		for (int i = 0; i < NewButton.colorstr.length; i++) {
			for (NewButton j : NewButton.values()) {
				if (j != NewButton.NB_NULL) {
					Assets.btns_pressed.put(NewButton.colorstr[i] + j.namestr(),
							g.newPixmap(String.format("btns/%s/pressed/images/nb%s.png",
									NewButton.colorstr[i], j.namestr()), PixmapFormat.ARGB8888));
				}
			}
		}

		Assets.aup = g.newPixmap("aup.png", PixmapFormat.ARGB8888);
		Assets.adown = g.newPixmap("adown.png", PixmapFormat.ARGB8888);
		Assets.aleft = g.newPixmap("aleft.png", PixmapFormat.ARGB8888);
		Assets.aright = g.newPixmap("aright.png", PixmapFormat.ARGB8888);

		Assets.bup = g.newPixmap("bup.png", PixmapFormat.ARGB8888);
		Assets.bdown = g.newPixmap("bdown.png", PixmapFormat.ARGB8888);
		Assets.bleft = g.newPixmap("bleft.png", PixmapFormat.ARGB8888);
		Assets.bright = g.newPixmap("bright.png", PixmapFormat.ARGB8888);


		final int Lasc = 3072;// Added by 教头20130729
		final int L1 = 182736;
		final int L2 = 243648;

		Assets.ascii12 = new byte[Lasc];// Added by 教头20130729
		Assets.charGBK12 = new byte[L1];
		Assets.charGBK16 = new byte[L2];

		BLGFileIO f = (BLGFileIO) Game.getInstance().getFileIO();
		InputStream is = null;
		try {
			is = f.readAsset("ascii.bin");// Added by 教头20130729
			is.read(Assets.ascii12);// Added by 教头20130729
			is = f.readAsset("gb12.bin");
			is.read(Assets.charGBK12);
			is = f.readAsset("gb16.bin");
			is.read(Assets.charGBK16);
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		Assets.bgm_battle = Game.getInstance().getAudio().newMusic("BGM/battle.mid");
	}


	public static void loadMaps() {
		BLGFileIO f = (BLGFileIO) getGame().getFileIO();
		InputStream is = null;

		final int MAP_COUNT = GmudMap.getMapCount();
		Gmud.maps = new GmudMap[MAP_COUNT];
//		Gmud.maps_bitmap = new Bitmap[3][];
		try {
			int i, j, k, l;
			for (i = 0; i < MAP_COUNT; i++) {
				is = f.readAsset("Maps/" + i + ".mapx");
				int width, height;
				width = is.read();
				height = is.read();

				Gmud.maps[i] = new GmudMap(width, height, i);
				for (j = 0; j < 3; j++) {
					for (k = 0; k < height; k++) {
						for (l = 0; l < width; l++) {
							int tx = is.read();
							int ty = is.read();
							Gmud.maps[i].setPoint(j, l, k, tx, ty);
						}
					}
				}

				is = f.readAsset("Maps/" + i + ".trg");
				width = is.read();
				height = is.read();
				for (k = 0; k < height; k++) {
					for (l = 0; l < width; l++) {
						int b1 = is.read();
						int b2 = is.read();
						int b3 = is.read();
						int b4 = is.read();

						if ((b1 & 2) != 0) {
							if((b1 & 1) != 0) {
								Gmud.maps[i].setWalkable(l, k, GmudMap.MP_SIMPLESCRIPT);
								Gmud.maps[i].setEvent(l, k, b2 + b3 * 256 + b4 * 256 * 256);
							} else {
								Gmud.maps[i].setWalkable(l, k, GmudMap.MP_CHANGETO);
								Gmud.maps[i].setEvent(l, k, b2 * 1000000 + b3 * 1000 + b4);
							}
						} else if ((b1 & 1) != 0) {
							Gmud.maps[i].setWalkable(l, k, GmudMap.MP_WALKABLE);
							if ((b2 & 1) != 0) {
								Gmud.maps[i].setWalkable(l, k, GmudMap.MP_NPC);
								Gmud.maps[i].setEvent(l, k, b3);
							}
						} else {
							if (b2 == 0) {
								Gmud.maps[i].setWalkable(l, k, GmudMap.MP_UNWALKABLE);
							} else {
								if ((b2 & 1) != 0) {
									Gmud.maps[i].setWalkable(l, k, GmudMap.MP_NPC);
								} else {
									Gmud.maps[i].setWalkable(l, k, GmudMap.MP_EVENT);
								}
								Gmud.maps[i].setEvent(l, k, b3);
							}
						}
					}
				}
				is = null;

				Music bgm;
				try {
					bgm = getGame().getAudio().newMusic("BGM/" + i + ".mid");
					if (bgm != null) {
						Assets.bgm_map.put(i, bgm);
					}
				} catch (Exception ignored) {
				}

			}

		} catch (IOException e) {
			Logger.e("map loading error!");
			e.printStackTrace();
		}

	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.ui.core.DialogScreen#onTouchDown(int, int)
	 */
	@Override
	protected void onTouchDown(int tx, int ty) {
	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.ui.core.DialogScreen#onTouchMove(int, int)
	 */
	@Override
	protected void onTouchMove(int tx, int ty) {
	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.ui.core.DialogScreen#onTouchUp(int, int)
	 */
	@Override
	protected void onTouchUp(int tx, int ty) {
	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.ui.core.DialogScreen#onClick(int, int)
	 */
	@Override
	protected void onClick(int tx, int ty) {
		if (b2) {
			getGame().popScreen();
			//			game.replaceCurrentScreen(ts);
		}
	}

	public static ArrayList<Npc> loadNpcJson() {
		BLGFileIO f = (BLGFileIO) Game.getInstance().getFileIO();
		BufferedReader in = null;

		try {
			in = new BufferedReader(new InputStreamReader(f.readAsset("data/Npc.dat")));
			String s = "";

			s = in.readLine();

//			Logger.json(s);

			Gson gson = new Gson();

			ArrayList<Npc> npcs = gson.fromJson(s, new TypeToken<ArrayList<Npc>>() {}.getType());

			for (int i = 0; i < npcs.size(); i++) {
				while (npcs.get(i).skills.length < Skill.getSkillCount()) {
					npcs.get(i).skills = Gmud.push_back(npcs.get(i).skills, 0);
				}
			}

			return npcs;

		} catch (IOException | JsonSyntaxException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return null;
	}

	public static ArrayList<ItemTemplate> loadItemJson() {
		BLGFileIO f = (BLGFileIO) getGame().getFileIO();
		BufferedReader in = null;

		try {
			in = new BufferedReader(new InputStreamReader(f.readAsset("data/Item.dat")));
			String s = "";

			s = in.readLine();

//			Logger.json(s);

			Gson gson = new Gson();

			return gson.fromJson(s, new TypeToken<ArrayList<ItemTemplate>>() {
			}.getType());

		} catch (IOException | JsonSyntaxException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}

		}
		Logger.e("读取物品数据失败！");
		return null;
	}

	static void loadSkillJson() {
		BLGFileIO f = (BLGFileIO) getGame().getFileIO();
		BufferedReader in = null;

		try {
			in = new BufferedReader(new InputStreamReader(f.readAsset("data/Skill.dat")));
			String s = "";

			s = in.readLine();

//			Logger.json(s);

			Gson gson = new Gson();


			Gmud.skill = gson.fromJson(s, Skill[].class);

			Logger.i("success!");

		} catch (IOException | JsonSyntaxException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	static void loadGestureJson() {
		BLGFileIO f = (BLGFileIO) getGame().getFileIO();
		BufferedReader in = null;

		try {
			in = new BufferedReader(new InputStreamReader(f.readAsset("data/Gesture.dat")));
			String s = "";

			s = in.readLine();

//			Logger.json(s);

			Gson gson = new Gson();


			Gmud.zs = gson.fromJson(s, new TypeToken<ArrayList<Gesture>>() {
			}.getType());

			Logger.i("success!");

		} catch (IOException e) {
			e.printStackTrace();
		} catch (JsonSyntaxException e2) {
			e2.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	static void loadConditionsJson() {
		BLGFileIO f = (BLGFileIO) getGame().getFileIO();
		BufferedReader in = null;

		try {
			in = new BufferedReader(new InputStreamReader(f.readAsset("data/conditions.dat")));
			String s = "";

			s = in.readLine();

//			Logger.json(s);

			Gson gson = new Gson();


			Gmud.conditions = gson.fromJson(s, new TypeToken<ArrayList<TriggerCondition>>() {
			}.getType());

			Logger.i("success!");

		} catch (IOException | JsonSyntaxException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	static void loadEventsJson() {
		BLGFileIO f = (BLGFileIO) getGame().getFileIO();
		BufferedReader in = null;

		try {
			in = new BufferedReader(new InputStreamReader(f.readAsset("data/events.dat")));
			String s = "";

			s = in.readLine();

//			Logger.json(s);

			Gson gson = new Gson();

			Gmud.events = gson.fromJson(s, new TypeToken<ArrayList<TriggerEvent>>() {
			}.getType());

			Logger.i("success!");

		} catch (IOException | JsonSyntaxException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	static void loadMEIJson() {
		BLGFileIO f = (BLGFileIO) getGame().getFileIO();
		BufferedReader in = null;

		try {
			in = new BufferedReader(new InputStreamReader(f.readAsset("data/MapExtraInfo.dat")));
			String s = "";

			s = in.readLine();

//			Logger.json(s);

			Gson gson = new Gson();

			ArrayList<MapExtraInfo> meis = gson.fromJson(s, new TypeToken<ArrayList<MapExtraInfo>>() {
			}.getType());

			for (GmudMap i : Gmud.maps) {
				if (meis.size() > i.id) {
					i.extraInfo = meis.get(i.id);
				} else {
					i.extraInfo = new MapExtraInfo();
				}
			}

			Logger.i("success!");

		} catch (IOException | JsonSyntaxException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	public static String[] loadSimpleScriptsJson() {
		BLGFileIO f = (BLGFileIO) Game.getInstance().getFileIO();
		BufferedReader in = null;

		String ss[] = new String[0];

		try {
			in = new BufferedReader(new InputStreamReader(f.readAsset("Maps/SimpleScripts.dat")));
			String s = "";

			s = in.readLine();
			Gson gson = new Gson();
			ss = gson.fromJson(s, String[].class);

		} catch (IOException | JsonSyntaxException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return ss;
	}

	public static String[] loadMapnameJson() {
		BLGFileIO f = (BLGFileIO) Game.getInstance().getFileIO();
		BufferedReader in = null;

		String ss[] = new String[0];

		try {
			in = new BufferedReader(new InputStreamReader(f.readAsset("Maps/MapName.dat")));
			String s = "";

			s = in.readLine();
			Gson gson = new Gson();
			ss = gson.fromJson(s, String[].class);

		} catch (IOException | JsonSyntaxException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return ss;
	}

	public static String[] loadFactionJson() {
		BLGFileIO f = (BLGFileIO) Game.getInstance().getFileIO();
		BufferedReader in = null;

		String ss[] = new String[0];

		try {
			in = new BufferedReader(new InputStreamReader(f.readAsset("data/factions.dat")));
			String s = "";

			s = in.readLine();
			Gson gson = new Gson();
			ss = gson.fromJson(s, String[].class);

		} catch (IOException | JsonSyntaxException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return ss;
	}
}
